// //util/ws.js

const WebSocket = require('ws')
const CreateSequelize = require('../sequelize')
let Sequelize = require('sequelize')
const { DataTypes, Op, where } = require('sequelize')
let sequelize = new CreateSequelize()
sequelize.init_sequeleze()
const records = sequelize.db.define('records', {
    uuid: {
        type: DataTypes.UUID,
        comment: '自增长id',
        defaultValue: Sequelize.UUIDV4
    },
    from_id: {
        type: DataTypes.STRING,
        comment: '发消息的人'
    },
    to_id: {
        type: DataTypes.STRING,
        comment: '收消息的人'
    },
    name: {
        type: DataTypes.STRING,
        comment: '用户备注'
    },
    msg: {
        type: DataTypes.STRING(10000),
        comment: '发送信息'
    },
    time: {
        type: DataTypes.STRING,
        comment: '发送时间'
    },
    headImg: {
        type: DataTypes.STRING,
        comment: '用户头像'
    },
    isRead: {
        type: DataTypes.INTEGER,
        comment: '已读未读消息 0未读,1已读)'
    }
}, {
    timestamps: true, // 开启时间戳
})
const usersWs = {}
class ws {
    static ws = WebSocket.Server //默认实例
    //初始化ws
    static init(server) {
        // 创建实例
        this.ws = new WebSocket.Server({
            server,
            path: '/ws'
        });
        this.ws.on('connection', async (moduleWS, req) => {
            console.log('和前端ws连接成功');
            usersWs[decodeURI(req.url.split('=')[1])] = moduleWS
            console.log(decodeURI(req.url.split('=')[1]), '----');
            //查找数据库聊天
            let newData = await records.findAll({})
            // //遍历是否有未读消息
            let notread = newData.filter((item) => {
                return item.isRead === 0
            })

            //forEach循环并改变消息
            notread.forEach(async item => {

                //定义
                let jsonMsg = {
                    from: item.from_id,
                    msg: item.msg
                }

                moduleWS.send(JSON.stringify(jsonMsg))  

                //更新已读消息
                await records.update({
                    isRead: 1
                }, {
                    where: {
                        to_id: req.url.split('=')[1]
                    }
                })
            })

            moduleWS.on('message', async (data) => {
                let { to_id, msg, headImg, name } = JSON.parse(data)
                /**
                 * from_id:发送人
                 * to_id:给谁发
                 * isRead:消息已读未读（0）是未读 （1)是已读
                 * headImg：用户头像
                 */
                let from_id = req.url.split('=')[1]
                let isRead = 0
                let time = Date.now()
                //写入MySQL聊天记录
                await records.create({
                    from_id, to_id, name, msg, time, isRead, headImg
                })


                //如果要发送的人在，那么久直接给他发
                if (usersWs[to_id]) {
                    //更新已读消息
                    await records.update({
                        isRead: 1
                    }, {
                        where: {
                            to_id: to_id
                        }
                    })
                    usersWs[to_id].send(JSON.stringify(msg))

                }
            })
        })
    }
}




module.exports = ws